home *** CD-ROM | disk | FTP | other *** search
- Path: news.mcs.net!mdp
- From: mdp@mika-sys.com (Michael D. Perry)
- Newsgroups: comp.lang.c
- Subject: Bitwise Operators, Help with please!
- Date: Sat, 10 Feb 96 23:43:58 GMT
- Organization: MIKA Systems
- Message-ID: <4fjaju$i1o_001@pr.mcs.net>
- NNTP-Posting-Host: mdp.pr.mcs.net
- X-Newsreader: News Xpress Version 1.0 Beta #4
-
- Hello All;
-
- I am trying to teach myself 'C' programming from a book which
- perhaps is not explaining the Bitwise Operators as well as I
- would desire in order to understand them.
-
- After going through a few examples the book is having me write a
- program that will pack som data and then unpak using bitwise
- operators. I have the packing down OK and can print the bits but
- am just not getting the Unpacking.
-
- What I want to do is to unpack each 'field' of a type short with
- the data as follows:
-
- Identification Job Type Gender
- ============== ======== ======
- bbbbbbbbb bbbbbb b
-
- and then be able to read the returned bits and conver them back
- to their original 'readable' form.
-
- Can someone help me with some code so I can at least see how this
- would be done and maybe understand it then?
-
- What I have so far is listed below and thanks for your
- assistance in advance.
-
- Mike
-
-
- = = = = = = = = = =
-
- #include <stdio.h>
- #include <limits.h>
-
- short create_employee_data(int, int, char);
- void bit_print(int);
- short unpak(int, int);
-
- main()
- {
- int id_no = 255;
- int job_type = 63;
- char gender = 'F';
- short employee;
-
- employee = create_employee_data(id_no,
- job_type,
- gender);
- bit_print(employee);
- printf("\n%d", char_unpak(employee, 32766));
- return 0;
- }
-
- short create_employee_data(int id_no,
- int job_type,
- char gender)
- {
- short employee = 0;
-
- employee |= (gender == 'm' || gender == 'M') ? 0 : 1;
- employee |= (job_type << 1);
- employee |= (id_no << 7);
- return employee;
- }
-
- void bit_print(int a)
- {
- int i;
- int n = sizeof(int) * CHAR_BIT;
- int mask = 1 << (n - 1);
-
- for (i = 1; i <= n; ++i)
- {
- putchar(((a & mask) == 0) ? '0' : '1');
- a <<= 1;
- if (i % CHAR_BIT == 0 && i < n)
- {
- putchar(' ');
- }
- }
- }
-
- short unpak(int emp, int move, unsigned mask)
- {
- return ((emp & mask)>> move);
- }
-
- -------------------------------------------------------------------
- Michael D. Perry | FIRST RULE OF INTELLIGENT TINKERING:
- MIKA Systems | Save all the parts.
- Glen Ellyn, Illinois | SATTINGER'S LAW:
- mdp@mika-sys.com | It works better if you plug it in.
- -------------------------------------------------------------------
-